<template>
  <div class="production_page">
    <div class="content">
      <div class="to_authenticate_tips" v-if="showTips">
        <i class="el-icon-warning warning_icon"></i>
        <span class="text">您尚未完成企业实名注册认证，请您准备好本人身份证件、营业执照、法定代表人身份证等资料信息</span>
        <span class="go_authenticate" @click="toAuthenticate">
          去认证
          <i class="el-icon-d-arrow-right"></i>
        </span>
        <img
          src="@/assets/production/index/close_icon.png"
          alt=""
          class="close_icon"
          @click="showTips = false"
        >
      </div>
      <div class="banner_box">
        <img
          src="@/assets/production/index/banner.png"
          alt=""
          class="banner_img"
        />
      </div>
      <div class="production_mod">
        <div class="production_mod_c">
          <ul class="production_list">
            <li class="production_item" v-for="(item, index) in list" :key="item.id">
              <div class="production_item_c">
                <img v-if="index === 0" src="@/assets/production/index/shu_xin_yi_dai.png" alt="" class="production_img">
                <img v-if="index === 1" src="@/assets/production/index/shu_xin_yi_rong.png" alt="" class="production_img">
                <img v-if="index === 2" src="@/assets/production/index/shu_xin_yi_lian.png" alt="" class="production_img">
                <div class="title_box">
                  <h3 class="title">
                    {{ item.projectName }}
                    <span class="status" v-if="Number(item.status) === 0">未开通</span>
                    <span class="status" v-if="Number(item.status) === 1">已停用</span>
                    <span class="status active" v-if="Number(item.status) === 2">已开通</span>
                  </h3>
                </div>
                <div class="desc" v-if="index === 0">依托中小微企业自身信用，结合大数据推荐和风险评估，向符合条件的中小微企业提供日常生产经营流动贷款。</div>
                <div class="desc" v-if="index === 1">依托于核心企业的产业链，借助互联网 、大数据技术， 对供应商与核心企业之间交易数据 、订单数据 、通过风险模型分析， 为供应商提供融资服务 。</div>
                <div class="desc" v-if="index === 2">依托核心企业的整体商业信用，由核心企业（或其成员单位）向供应商开具电子债权凭证（可拆分、可流转、可融资、可持有）；</div>
                <div class="advantage_list">
                  <div class="advantage_item">
                    <img src="@/assets/production/index/advantage_1.png" alt="" class="icon">
                    在线秒批
                  </div>
                  <div class="advantage_item">
                    <img src="@/assets/production/index/advantage_2.png" alt="" class="icon">
                    极速到账
                  </div>
                  <div class="advantage_item">
                    <img src="@/assets/production/index/advantage_3.png" alt="" class="icon">
                    循环额度
                  </div>
                </div>
                <el-button
                  :disabled="Number(item.status) === 1"
                  type="primary"
                  class="btn"
                  @click="productionClick(item)"
                >
                  立即进入
                </el-button>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <Copyright color="rgba(153, 153, 153, 1)" />
    </div>
    <!-- <el-dialog
      class="submit_success_dialog dialog"
      title="温馨提示"
      width="50%"
      :visible="operationDialogVisible"
      :close-on-click-modal="false"
      @close="operationDialogVisible = false"
    >
      <div class="dialog_c">
        <h5 class="title">企业还未添加运营人员</h5>
        <el-button type="primary" class="btn" @click="addOperationDialogSure">确 定</el-button>
      </div>
    </el-dialog> -->
    <CustomDialog
      height="200px"
      :dialogBg="true"
      :visible="operationDialogVisible"
      title="温馨提示"
      @close="operationDialogVisible = false"
    >
      <div class="mask_text">企业还未添加运营人员</div>
      <button class="mask_btn" @click="addOperationDialogSure">确定</button>
    </CustomDialog>
    <!-- <el-dialog
      class="submit_success_dialog dialog"
      title="温馨提示"
      width="50%"
      :visible="authenticateDialogVisible"
      :close-on-click-modal="false"
      @close="authenticateDialogVisible = false"
    >
      <div class="dialog_c">
        <h5 class="title">您当前暂未完成认证，请先进行认证。</h5>
        <el-button type="primary" class="btn" @click="toAuthenticate">去认证</el-button>
      </div>
    </el-dialog> -->
    <CustomDialog
      height="200px"
      :dialogBg="true"
      :visible="authenticateDialogVisible"
      title="温馨提示"
      @close="authenticateDialogVisible = false"
    >
      <div class="mask_text">您当前暂未完成认证，请先进行认证</div>
      <button class="mask_btn" @click="toAuthenticate">去认证</button>
    </CustomDialog>
    <!-- <el-dialog
      class="submit_success_dialog dialog"
      title="温馨提示"
      width="50%"
      :visible="productionDialogVisible"
      :close-on-click-modal="false"
      @close="productionDialogVisible = false"
    >
      <div class="dialog_c">
        <h5 class="title">您当前暂未开通产品，请先进行产品开通</h5>
        <el-form ref="productionDialogForm" :model="productionDialogForm" :rules="productionDialogFormRules">
          <div class="flex justify_center">
            <el-form-item prop="agreement" style="text-align: center;">
              <el-checkbox v-model="productionDialogForm.agreement">我已阅读并同意</el-checkbox>
              <a
                class="color_theme"
                :href="baseURL + agreement3Dowload.fileUrl"
                target="_blank"
              >《数信易融产品开通协议》</a>
              <a
                class="color_theme"
                :href="baseURL + agreement6Dowload.fileUrl"
                target="_blank"
                v-if="companyDetailObj.enterpriseType && Number(companyDetailObj.enterpriseType) === 10"
              >《项目管理合作服务协议》</a>
            </el-form-item>
          </div>
        </el-form>
        <el-button type="primary" class="btn" @click="productionDialogSubmit">确 定</el-button>
      </div>
    </el-dialog> -->
    <CustomDialog
      :dialogBg="true"
      width="500px"
      :visible="productionDialogVisible"
      title="温馨提示"
      :buttonArray="[
        {
          text: '取消',
          clickFn: closeProductionDialog
        },
        {
          text: '确定',
          clickFn: productionDialogSubmit
        }
      ]"
      @close="closeProductionDialog"
    >
      <div class="mask_text">您当前暂未开通产品，请先进行产品开通</div>
      <el-form ref="productionDialogForm" :model="productionDialogForm" :rules="productionDialogFormRules">
        <div class="flex justify_center">
          <el-form-item prop="agreement" style="text-align: center;">
            <el-checkbox v-model="productionDialogForm.agreement">我已阅读并同意</el-checkbox>
            <a
              class="color_theme"
              :href="baseURL + agreement3Dowload.fileUrl"
              target="_blank"
            >《数信易融产品开通协议》</a>
            <a
              class="color_theme"
              :href="baseURL + agreement6Dowload.fileUrl"
              target="_blank"
              v-if="companyDetailObj.enterpriseType && Number(companyDetailObj.enterpriseType) === 10"
            >《项目管理合作服务协议》</a>
          </el-form-item>
        </div>
      </el-form>
    </CustomDialog>
    <!-- <el-dialog
      class="submit_success_dialog dialog"
      title="签署协议"
      width="50%"
      :visible="agreementDialogVisible"
      :close-on-click-modal="false"
      @close="closeAgreementDialog"
    >
      <div class="dialog_c">
        <el-form
          ref="agreementDialogForm"
          :model="agreementDialogForm"
          :rules="agreementDialogFormRules"
          label-width="140px"
          label-position="right"
        >
          <el-form-item prop="agreement">
            <el-checkbox v-model="agreementDialogForm.agreement">我已阅读并知晓同意</el-checkbox>
            <a
              class="color_theme"
              :href="baseURL + agreement3Dowload.fileUrl"
              target="_blank"
            >《数信易融产品开通协议》</a>
            <a
              class="color_theme"
              :href="baseURL + agreement6Dowload.fileUrl"
              target="_blank"
              v-if="companyDetailObj.data && companyDetailObj.data.enterpriseType && Number(companyDetailObj.data.enterpriseType) === 10"
            >《项目管理合作服务协议》</a>
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="createPhonenumber"></el-input>
          </el-form-item>
          <el-form-item label="短信验证码" prop="code">
            <div class="code_line">
              <el-input
                type="text"
                placeholder="请输入短信验证码"
                v-model="agreementDialogForm.code"
              ></el-input>
              <el-button
                class="get_code"
                type="primary"
                :loading="codeLoading"
                @click="getCode"
              >{{ sNumber > -1 ? sNumber + 's' : '获取验证码' }}</el-button>
            </div>
          </el-form-item>
        </el-form>
        <el-button type="primary" class="btn" @click="agreementClick">确 定</el-button>
      </div>
    </el-dialog> -->
    <CustomDialog
      :dialogBg="true"
      title="签署协议"
      width="700px"
      :visible="agreementDialogVisible"
      :buttonArray="[
        {
          text: '取消',
          clickFn: closeAgreementDialog,
        },
        {
          text: '确定',
          clickFn: agreementClick,
        }
      ]"
      @close="closeAgreementDialog"
    >
      <el-form
        class="mask_dialog_c"
        ref="agreementDialogForm"
        :model="agreementDialogForm"
        :rules="agreementDialogFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item prop="agreement">
          <el-checkbox v-model="agreementDialogForm.agreement">我已阅读并知晓同意</el-checkbox>
          <a
            class="color_theme"
            :href="baseURL + agreement3Dowload.fileUrl"
            target="_blank"
          >《数信易融产品开通协议》</a>
          <a
            class="color_theme"
            :href="baseURL + agreement6Dowload.fileUrl"
            target="_blank"
            v-if="companyDetailObj.enterpriseType && Number(companyDetailObj.enterpriseType) === 10"
          >《项目管理合作服务协议》</a>
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input :disabled="true" :value="createPhonenumber"></el-input>
        </el-form-item>
        <el-form-item label="短信验证码" prop="code">
          <div class="code_line">
            <el-input
              type="text"
              placeholder="请输入短信验证码"
              v-model="agreementDialogForm.code"
            ></el-input>
            <el-button
              class="get_code"
              type="primary"
              :loading="codeLoading"
              @click="getCode"
            >{{ sNumber > -1 ? sNumber + 's' : '获取验证码' }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </CustomDialog>
  </div>
</template>

<script>
import { getCompanyMsg, getProductionList, openProduction } from '@/api/production'
import { operationList, getCode } from '@/api/companyManage'
import Copyright from '@/customComponents/copyright'
import { downloadTemplate } from "@/api/authenticate"
import CustomDialog from '@/customComponents/dialog'

export default {
  components: {
    Copyright,
    CustomDialog,
  },
  data() {
    return {
      showTips: false,
      // 状态（//0未开通 1停用（按钮不可点击）2：已开通',
      list: [],
      operationDialogVisible: false,
      authenticateDialogVisible: false,
      companyDetailObj: {
        enterpriseBank: {},
        adminOperation: {},
      },
      createPhonenumber: '',
      productionDialogVisible: false,
      productionDialogForm: {
        agreement: false,
      },
      productionDialogFormRules: {
        agreement: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                callback()
              } else {
                callback('请勾选协议')
              }
            },
            trigger: ['change', 'blur']
          }
        ]
      },
      // 签署协议
      agreementDialogVisible: false,
      agreementDialogForm: {
        agreement: false,
        // phonenumber: '',
        code: '',
        uuid: '',
      },
      agreementDialogFormRules: {
        agreement: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                callback()
              } else {
                callback('请勾选协议')
              }
            },
            trigger: ['change', 'blur']
          }
        ],
        code: [
        { required: true, trigger: ['change', 'blur'], message: '请输入短信验证码' },
        ],
      },
      baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :
        process.env.VUE_APP_HTTP_REQUEST_ADDRESS,
      agreement3Dowload: {},
      agreement6Dowload: {},
      currentProductionId: '', // 当前点中的产品id
      codeLoading: false,
      sNumber: -1, // 倒计时
      timer: null, // 倒计时
    }
  },
  watch: {
    'companyDetailObj.adminOperation.contactPhone': {
      handler: function (newVal) {
        if (newVal) {
          this.createPhonenumber = newVal?.slice(0, 3) +
          "*".repeat(4) +
          newVal?.slice(-4)
        }
      },
      deep: true
    },
  },
  mounted() {
    this.downloadTemplate(3).then((res) => {
      this.agreement3Dowload = res.data;
    }); // 数信易融产品开通协议
    this.downloadTemplate(6).then((res) => {
      this.agreement6Dowload = res.data;
    }); // 项目管理合作服务协议
    this.getProductionList()
    getCompanyMsg().then((res) => {
      this.companyDetailObj = res.data
      if (res.data.status === '0') {
        this.showTips = true
      } else if (res.data.status === '2') {
        this.getOperationList()
      }
    }).catch((error) => {
      if (error.code === 201) {
        this.showTips = true
      }
    })
  },
  methods: {
    // 获取产品列表
    getProductionList() {
      getProductionList().then((res) => {
        if (res.code === 200) {
          this.list = res.rows
        }
      })
    },
    // 去认证
    toAuthenticate() {
      return new Promise((resolve, reject) => {
        getCompanyMsg().then((res) => {
          // 状态 0：未认证 1：等待审核 2：已认证 3：认证失败
          switch(res?.data?.status) {
            case '0':
              this.$router.push({
                path: '/authenticate/add',
              })
              reject()
              break;
            case '1':
            case '3':
              this.$router.push({
                path: '/authenticate/result'
              })
              reject()
              break;
            case '2':
              resolve()
              break;
          }
        }).catch((error) => {
          if (error.code === 201) { // 未认证201
            this.$router.push({
              path: '/authenticate/add',
            })
          }
          reject()
        })
      })
    },
    // 获取运营人员列表
    getOperationList() {
      return new Promise((resolve, reject) => {
        operationList().then((res) => {
          if (res?.code === 200 && res?.rows?.length) {
            resolve()
          } else {
            this.operationDialogVisible = true
            reject()
          }
        }).catch(() => {
          reject()
        })
      })
    },
    // 开通产品dialog
    showOpenProductionDialog() {
      this.productionDialogVisible = true
      return Promise.reject()
    },
    // 点击产品
    productionClick(item) {
      this.currentProductionId = item.id
      const promiseArr = [
        this.toAuthenticate,
        this.getOperationList,
        ...(item.status === '0' ? [this.showOpenProductionDialog] : []),
      ]
      promiseArr.reduce((resPromise, fn, index) => {
        return resPromise.then(() => {
          if (index === (promiseArr.length - 1)) {
            return fn(item.id).then(() => {
              this.$router.push({
                path: '/productionCenter/workbenchHome'
              })
            })
          } else {
            return fn()
          }
        })

      }, Promise.resolve())
    },
    // 去添加运营人员页面
    addOperationDialogSure() {
      this.operationDialogVisible = false
      this.$router.push({
        path: '/companyManage/addOperation'
      })
    },
    // 下载模板
    downloadTemplate(id) {
      return new Promise((resolve, reject) => {
        downloadTemplate(id).then((res) => {
          resolve(res);
        });
      });
    },
    // 同意开通协议
    productionDialogSubmit() {
      this.$refs.productionDialogForm.validate((valid) => {
        if (valid) {
          this.productionDialogVisible = false
          this.productionDialogForm.agreement = false
          this.agreementDialogVisible = true
        }
      })
    },
    // 关闭同意开通协议
    closeProductionDialog() {
      this.productionDialogVisible = false
    },
    countFn() {
      this.timer = setTimeout(() => {
        if (this.sNumber > -1) {
          --this.sNumber
          this.countFn()
        } else {
          clearTimeout(this.timer)
          this.timer = null
        }
      }, 1000);
    },
    countDown() {
      this.sNumber = 60
      this.countFn()
    },
    // 开通产品获取code
    getCode() {
      this.codeLoading = true
      getCode(5).then((res) => {
        this.codeLoading = false
        this.agreementDialogForm.uuid = res.uuid;
        this.countDown()
      }).catch(() => {
        this.codeLoading = false
      });
    },
    // 开通产品
    openProduction(id) {
      return new Promise((resolve, reject) => {
        openProduction({
          projectConfigId: id,
          code: this.agreementDialogForm.code,
          uuid: this.agreementDialogForm.uuid
        }).then((res) => {
          this.$message({
            type: 'success',
            message: '产品开通成功',
            onClose: () => {
              this.$router.push({
                path: '/productionCenter/workbenchHome'
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '产品开通失败'
          })
          this.agreementDialogForm.code = ''
          this.agreementDialogForm.uuid = ''
        })
      })
    },
    // 签署协议
    agreementClick() {
      this.$refs.agreementDialogForm.validate((valid) => {
        if (valid) {
          this.openProduction(this.currentProductionId)
        }
      })
    },
    // 关闭弹窗
    closeAgreementDialog() {
      this.agreementDialogVisible = false
      this.$refs.agreementDialogForm.resetFields()
    }
  },
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/px2rem.scss';
@import "@/assets/styles/variables.scss";

.content {
  background-color: #fff;
  .to_authenticate_tips {
    position: fixed;
    top: 80px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 2;
    display: flex;
    align-items: center;
    height: 34px;
    background-color: #FFFCEC;
    border: 1px solid #FDDB99;
    border-radius: 6px;
    padding: 0 12px 0 16px;
    color: #FF8807;
    font-size: 14px;
    width: 798px;
    .warning_icon {
      font-size: 14px;
      color: #FF8807;
      margin-right: 7px;
    }
    .text {
      flex-shrink: 0;
    }
    .go_authenticate {
      cursor: pointer;
      margin-left: 13px;
      margin-right: 48px;
      color: $theme;
      flex-shrink: 0;
    }
    .close_icon {
      display: block;
      width: 14px;
      height: 14px;
    }
  }
  .banner_box {
    .banner_img {
      display: block;
      width: 100%;
      height: auto;
    }
  }
  .production_mod {
    display: flex;
    justify-content: center;
    margin-bottom: 92px;
    .production_mod_c {
      width: px2rem(1400);
      .production_list {
        display: flex;
        flex-wrap: wrap;
        margin-top: px2rem(105);
        margin-left: px2rem(-35);
        margin-right: px2rem(-35);
        .production_item {
          width: 33.33%;
          height: px2rem(466);
          display: flex;
          align-items: flex-end;
          padding: px2rem(35);
          font-size: px2rem(16);
          &:last-child {
            margin-right: 0;
          }
          .production_item_c {
            // width: 420px;
            height: px2rem(396);
            padding: 0 px2rem(30);
            box-sizing: border-box;
            background: linear-gradient( 180deg, #FFFFFF 0%, #FFFFFF 100%);
            box-shadow: 0px 2px 16px 0px rgba(7,71,191,0.24);
            border-radius: px2rem(20);
            position: relative;
            .production_img {
              display: block;
              width: px2rem(160);
              height: px2rem(160);
              position: absolute;
              left: 50%;
              transform: translate(-50%, -50%);
              &:hover {
                transform: translate(-50%, -50%) scale(1.2);
              }
            }
            .title_box {
              display: flex;
              justify-content: center;
              .title {
                margin-top: px2rem(120);
                margin-bottom: px2rem(30);
                color: #333;
                font-size: px2rem(30);
                font-weight: 600;
                text-align: center;
                height: px2rem(30);
                line-height: px2rem(30);
                position: relative;
                .status {
                  position: absolute;
                  top: px2rem(-10);
                  right: px2rem(-50);
                  display: block;
                  width: px2rem(50);
                  height: px2rem(24);
                  line-height: px2rem(24);
                  background: linear-gradient( 90deg, #CDCFD1 0%, #C8CBCD 100%);
                  border-radius: px2rem(13) px2rem(13) px2rem(13) 0;
                  color: #fff;
                  font-size: px2rem(12);
                  &.active {
                    background: linear-gradient( 90deg, #55A1FC 0%, #0058FF 100%);
                  }
                }
              }
            }
            .desc {
              color: #555;
              font-size: px2rem(14);
              margin-bottom: px2rem(20);
              line-height: px2rem(22);
              height: px2rem(66);
            }
            .advantage_list {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: px2rem(30);
              .advantage_item {
                display: flex;
                align-items: center;
                color: $theme;
                font-size: px2rem(14);
                .icon {
                  display: block;
                  width: px2rem(20);
                  height: px2rem(20);
                  margin-right: px2rem(4);
                }
              }
            }
            .btn {
              border: none;
              padding: 0;
              width: 100%;
              height: px2rem(40);
              line-height: px2rem(40);
              background: linear-gradient( 90deg, #0058FF 0%, #69ADFF 100%);
              border-radius: px2rem(4);
            }
          }
        }
      }
    }
  }
}
.mask_text {
  text-align: center;
  margin: 22px auto 24px;
  color: #032944;
  font-size: 16px;
  font-weight: 500;
}
.mask_btn {
  display: block;
  margin: 0 auto;
  outline: none;
  width: 82px;
  height: 32px;
  border-radius: 3px;
  border: none;
  background-color: $theme;
  line-height: 32px;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  &:hover {
    background-color: #508DFF;
  }
}
.mask_dialog_c {
  .code_line {
    display: flex;
    .get_code {
      margin-left: 24px;
    }
  }
}
// .dialog {
//   font-size: 16px;
//   .dialog_c {
//     padding: 40px;
//   }
//   .title {
//     text-align: center;
//     color: $theme;
//     font-size: 28px;
//     font-weight: 500;
//     margin-bottom: 60px;
//   }
//   .sub_title {
//     margin-top: 30;
//     margin-bottom: 60px;
//     text-align: center;
//     color: #333;
//     font-size: 18px;
//   }
//   .code_line {
//     display: flex;
//     .get_code {
//       margin-left: 24px;
//     }
//   }
//   .btn {
//     width: 140px;
//     margin: 50px auto 0;
//     display: block;
//   }
// }
.color_theme {
  color: $theme;
}
.flex {
  display: flex;
}
.justify_center {
  justify-content: center;
}
.m_t_50 {
  margin-top: 50px;
}
</style>
